﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public abstract class RZUICtrlTemplate<TUIView> : RZUIBaseCtrl where TUIView : RZUIBaseView
{
    protected RZUIVo uivo;
    protected TUIView view;

    public RZUICtrlTemplate(RZUIVo vo)
    {
        uivo = vo;
        view = null;
        isShow = false;
        isLogicShow = false;
        isLoadingRes = false;
        isUIRelationShip = false;
    }

    public bool IsUILoaded { get { return view != null; } }

    public override void CreateUI ()
    {
        if (isLoadingRes || IsUILoaded) return;
        loadUI ();
    }

    public override void DestroyUI ()
    {
        if (view == null) return;

        //删除 UIRemoveCanvas 事件
        view.CtrlDestroy ();
        destroyed ();

        var desObj = view;

        view = null;
        isShow = false;
        isLogicShow = false;
        isLoadingRes = false;
        userData = null;
        GameObject.Destroy (desObj.gameObject);
    }

    public override bool Show ()
    {
        isLogicShow = true;
        if (isLoadingRes || !IsUILoaded) return false;

        isShow = true;
        view.Show ();
        showed ();
        return true;
    }

    public override void Hide ()
    {
        isLogicShow = false;
        isShow = false;

        hided ();

        if (view != null) view.Hide();
    }

   

    public override void Link (GameObject obj)
    {
        var T_view = obj.GetComponent<TUIView> ();
        if(T_view != null && view != T_view) DestroyUI ();

        isLogicShow = true;
        isLoadingRes = false;
        isShow = true;

        view = obj.GetComponent<TUIView> ();
        view.Init (this, uivo);

        created ();
    }

    public override bool CompareView (RZUIBaseView _view)
    {
        return view == _view;
    }

    protected virtual void clickCloseUI()
    {
        // UIHide
    }
    public virtual void showed () { }
    protected virtual void created() { }
    protected virtual void destroyed() { }
    protected virtual void hided() { }

    protected virtual void loadUI ()
    {
        isLoadingRes = true;
        var asset = Resources.Load<GameObject> (uivo.Url); // 
        //loadOver (asset as GameObject);
    }

    private void loadOver(GameObject prefab)
    {
        isLoadingRes = false;

        GameObject obj = GameObject.Instantiate (prefab);
        view = obj.GetComponent<TUIView> ();
        view.Init (this, uivo);

        created ();
        if(isLogicShow)
        {
            // UI Show
        }
    } 
}
